package com.zyd.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * 双工长连接Netty服务端
 */
public class DuplexNettyServer implements InitializingBean, DisposableBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(DuplexNettyServer.class);

    private int port;

    private ServerBootstrap serverBootstrap;

    private ChannelFuture channelFuture;

    private EventLoopGroup group = new NioEventLoopGroup();

    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(group);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline ch = channel.pipeline();
                    // 以("\n")为结尾分割的 解码器
                    ch.addLast("framer", new DelimiterBasedFrameDecoder(8192, 
                            Delimiters.lineDelimiter()));
                    // 解码和编码，应和客户端一致
                    ch.addLast("decoder", new StringDecoder());
                    ch.addLast("encoder", new StringEncoder());
                    ch.addLast("handler", new NettyServerHandler());// 服务端业务逻辑
                }
            }); //设置过滤器
            // 服务器绑定端口监听
            channelFuture = serverBootstrap.bind(port).sync();
            LOGGER.info("基站接收端口启动成功,port:" + port);
        } catch (Exception e) {
            LOGGER.error(port + "", e);
        }
    }


    @Override
    public void destroy() throws Exception {
        try {
            channelFuture.channel().close();
            group.shutdownGracefully(); ////关闭EventLoopGroup，释放掉所有资源包括创建的线程
        } catch (Exception e) {
            LOGGER.error("", e);
        }
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}
